package ikar.nrd.model;

import ikar.nrd.fillingref.generator.NewFillingRefProcessor;
import ikar.nrd.fillingref.generator.XSDProcessor;

import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;

import org.w3c.dom.Document;

public class FillingRefTreeModelFactory {

	private String rootElementName;
	public final static String DEFAULT_ROOT_FPML_NODE_NAME = "nonpublicExecutionReport";

	public FillingRefTreeModelFactory() {
	}

	public TreeModel createTreeModelFromXsd(String xsdTypeName, String xmlRootNodeName, String patternId) {
		initNamespacesURI();
		XSDProcessor xsdProcessor = new XSDProcessor(patternId);
		try {
			return new DefaultTreeModel(xsdProcessor.getXsdElementHierarchy(xsdTypeName, xmlRootNodeName, patternId));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

	public TreeModel createTreeModelFromXml(Document doc, String patternId) {
		initNamespacesURI();
		NewFillingRefProcessor fillProcessor = new NewFillingRefProcessor(patternId);
		DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode(new FillingRef("", "", getRootElementName(), patternId));
		fillProcessor.loadXmlSchemasTree(doc, rootNode);
		return new DefaultTreeModel(rootNode);
	}

	private void initNamespacesURI() {
		XmlNamespaceManager.add("http://www.fpml.org/FpML-5/recordkeeping/nsd-ext", "nsdext");
		XmlNamespaceManager.add("http://www.fpml.org/FpML-5/recordkeeping", "nsd");
		XmlNamespaceManager.add("http://www.fpml.org/FpML-5/ext", "fpmlext");
	}

	public String getRootElementName() {
		return rootElementName == null || rootElementName.length() == 0 ? DEFAULT_ROOT_FPML_NODE_NAME : rootElementName;
	}

	public void setRootElementName(String rootElementName) {
		this.rootElementName = rootElementName;
	}


}
